$(function() {

    //首页点击加入购物车 
    $('.goodsList ol').on('click', '.addCar', function() {
            var goodsId = $(this).parent().attr('data-id')

            addShoppingCar(goodsId)
            getPurchasedDataAndRender()

        })
        //首页热销模块添加进购物车
    $('.hotSale ol').on('click', '.addCar', function() {
        var goodsId = $(this).parent().attr('data-id')
        addShoppingCar(goodsId)
        getPurchasedDataAndRender()
    })  

    //列表页添加进购物车
    $('.goods_box ul').on('click', '.addCar', function() {
            var goodsId = $(this).parent().attr('data-id')
            addShoppingCar(goodsId)
            getPurchasedDataAndRender()
        })
        //商品详情页添加到购物车
    $('.right .purchaseBox .addShoppingCar').unbind('click').click(function() {
        var goodsId = $(this).parent().attr('data-id')
        addShoppingCar(goodsId)
        getPurchasedDataAndRender()
    })



    //添加进购物车
    function addShoppingCar(goodsId) {
        var goodsArr = JSON.parse($.cookie('goods'))
            // console.log(goodsArr);
        var first = goodsArr == null ? true : false
        if (first) {
            $.cookie('goods', JSON.stringify([{ id: goodsId, num: 1 }]), {
                expires: 7,
                path: '/'
            })
        } else {
            var same = false
            for (var i = 0; i < goodsArr.length; i++) {
                if (goodsArr[i]['id'] === goodsId) {
                    same = true
                    break
                }
            }
            same ? goodsArr[i]['num']++ : goodsArr.push({ id: goodsId, num: 1 })
            $.cookie('goods', JSON.stringify(goodsArr), {
                expires: 7,
                path: '/'

            })
        }
    }




    //删除某种商品
    
    $('.asideCar .goods').on('click', '#delGoods', function() {
        var buyGoods = JSON.parse($.cookie('goods'))
        var id = $(this).attr('data-id');
        for (var i = 0; i < buyGoods.length; i++) {
            if (buyGoods[i]['id'] == Number(id)) {
                buyGoods.splice(i, 1)
                    // console.log(buyGoods);
                break
            }
        }
        $.cookie('goods', JSON.stringify(buyGoods), {
            expires: 7,
            path: '/'

        })
        $(this).parent().parent().parent().remove()
        getPurchasedDataAndRender()

    })

    //清空购物车
    $('.footer #clearCar').unbind('click').click(function () {
        console.log($.cookie('goods'));
        $.cookie('goods', null)
        // getPurchasedDataAndRender()
        console.log($.cookie('goods'));

    })


    var selectAll = false
    var allCheckedFlag = []

    $('#selectAll').unbind('click').click(function (e) {
        var selects = $('.carGoods').children().length
        if ($(this).is(":checked")) {
            for (var i = 0; i < selects; i++) {
                $(`.carGoods .goodsItem:eq(${i}) input[type='checkbox']`).attr('checked', 'checked')
                allCheckedFlag.push('true')
                console.log(allCheckedFlag);

                getAllGoodsPricePvNum(i)
            }
            $('.selectedNum i').text(selects)
        } else if (!$(this).is(":checked")){
            for (var j = 0; j < selects; j++) {
                console.log('quanxuan');

                $(`.carGoods .goodsItem:eq(${j}) input[type='checkbox']`).attr('checked', null)
                console.log($(`.carGoods .goodsItem:eq(${j}) input[type='checkbox']`).is(":checked"));

                allCheckedFlag.pop('true')
            }
            $('.selectedPVAndNum .goodsNums i').text(0)
            $('.selectedPVAndNum .goodsPVs i').text(0)
            $('.selectedPriceAll em i').text(0)
            $('.selectedNum i').text(0)
        }
    })


    //购物车页面删除商品     //购物车页面，商品增加   //购物车商品数量减少   //商品列表复选框
    $('.carGoods').unbind('click').on('click', '.del', function () {
        var buyGoods = JSON.parse($.cookie('goods'))
        var id = $(this).attr('data-id');
        for (var i = 0; i < buyGoods.length; i++) {
            if (buyGoods[i]['id'] == Number(id)) {
                buyGoods.splice(i, 1)
                break
            }
        }
        $.cookie('goods', JSON.stringify(buyGoods), {
            expires: 7,
            path: '/'
        })
        $(this).parent().remove()
        getPurchasedDataAndRender()

    }).on('click', '.add', function (){
        var buyGoods = JSON.parse($.cookie('goods'))
        var id = $(this).parent().attr('data-id');
        for (var i = 0; i < buyGoods.length; i++) {
            if (buyGoods[i]['id'] == Number(id)) {
                buyGoods[i]['num']++
                break
            }
        }
        $.cookie('goods', JSON.stringify(buyGoods), {
            expires: 7,
            path: '/'

        })
        getPurchasedDataAndRender()

    }).on('click', '.reduce', function () {
        var buyGoods = JSON.parse($.cookie('goods'))
        var id = $(this).parent().attr('data-id');
        for (var i = 0; i < buyGoods.length; i++) {
            if (buyGoods[i]['num'] > 1 && buyGoods[i]['id'] == Number(id)) {
                buyGoods[i]['num']--
                break
            }
        }
        $.cookie('goods', JSON.stringify(buyGoods), {
            expires: 7,
            path: '/'

        })
        getPurchasedDataAndRender()
    }).on('click', ".goodsItem input[type='checkbox']", function () {

        var i = $(this).parent().index()
        if ($(`.carGoods .goodsItem:eq(${i}) input[type='checkbox']`).is(":checked")) {
            allCheckedFlag.push('true')
        } else {

            allCheckedFlag.pop('true')

        }
        getAllGoodsPricePvNum(i)
        $('.selectedNum i').text(allCheckedFlag.length)
        isSelectAll()
    })



  
    getPurchasedDataAndRender()
        //获取全部的数据并通过Id查找想要购买商品的详细信息

    function getPurchasedDataAndRender() {
       
        var buyGoods = JSON.parse($.cookie('goods')) ? JSON.parse($.cookie('goods')) : []
     

        
        $.ajax({
            type: "get",
            url: "/shoppingCarData",
            dataType: "json",
            success: function(response) {
                response.forEach((item) => {

                        buyGoods.forEach((buyGoodsItem) => {
                            if (item.id == buyGoodsItem.id) {
                                buyGoodsItem.imgUrl = item.imgUrl
                                buyGoodsItem.code = item.code
                                buyGoodsItem.price = item.price
                                buyGoodsItem.displayName = item.displayName
                                buyGoodsItem.pv = item.pv
                            }
                        })
                    })
                    // console.log(buyGoods); //得到所有的想要购买的商品信息
                    // 渲染数据到侧边购物车
                renderAsideShoppingCar(buyGoods)
                getNum(buyGoods)
                renderShoppingCar(buyGoods)
                getAllGoodsPricePvNum()

            }
        });

    }



    //渲染购物车页面

    function renderShoppingCar(buyGoods) {

        var str = ''
        buyGoods.forEach(item => {
            var price = `${item.price}` * `${item.num}`
            var pv = `${item.pv}` * `${item.num}`
            str = `
        <div class="goodsItem">
            <input type="checkbox" name="" id="">
            <div class="goodsIntroduce">
                <img src="${item.imgUrl}" alt="">
                <div class="goodsIntroRight">
                    <div class="goodsTitle">
                        ${item.displayName}
                    </div>
                    <div class="goodsCode">
                        产品编码：${item.code}
                    </div>
                </div>
            </div>
            <div class="priceAndPV">
                <div class="price">
                    ￥<i>${item.price}</i>.00
                </div>
                <div class="pv">
                    积分（pv）<i>${item.pv}</i>
                </div>
            </div>
            <div class="num">
                <span data-id='${item.id}'><i class="reduce">-</i><em id="purchaseNum">${item.num}</em><i class="add">+</i></span>
            </div>
            <div class="pricePVAll">
                <div class="priceAll">￥ <em>${price}.00</em> </div>
                <div class="pvAll">积分（pv）<i>${pv}</i> </div>
            </div>
            <div class="operation">
                <span class="del" data-id='${item.id}'>删除</span>
                <span class="collection">加入我的收藏</span>
            </div>
        </div>
        ` 

            
            for (var i = 0; i < $('.goodsItem').length; i++) {
                if ($('.operation .del').eq(i).attr('data-id') == `${item.id}`)
                    $('.goodsItem').eq(i).remove()
            }
            $('.carGoods').append(str)

        })

    }

    //判断是否全选
    function isSelectAll(){
        var flag11 = $(`.carGoods .goodsItem`).length == allCheckedFlag.length
        if (flag11)
        {
            selectAll = true
            $('#selectAll').attr('checked', 'checked')

        }
        else{
            selectAll = false
            $('#selectAll').attr('checked', null)

        }
    }
    //计算商品列表大的总积分总金额
    function getAllGoodsPricePvNum(i) {
        var price = Number($('.selectedPriceAll em i').text())
        var pv = Number($('.selectedPVAndNum .goodsPVs i').text())
        var goodsNum = Number($('.selectedPVAndNum .goodsNums i').text())
        if ($(`.carGoods .goodsItem:eq(${i}) input[type='checkbox']`).is(":checked")){
            price += Number($(`.carGoods .goodsItem:eq(${i}) .pricePVAll .priceAll em`).text())
            pv += Number($(`.carGoods .goodsItem:eq(${i}) .pricePVAll .pvAll i`).text())
            goodsNum += Number($(`.carGoods .goodsItem:eq(${i}) .num #purchaseNum`).text())
        }else{
            price -= Number($(`.carGoods .goodsItem:eq(${i}) .pricePVAll .priceAll em`).text())
            pv -= Number($(`.carGoods .goodsItem:eq(${i}) .pricePVAll .pvAll i`).text())
            goodsNum -= Number($(`.carGoods .goodsItem:eq(${i}) .num #purchaseNum`).text())
        }
        $('.selectedPVAndNum .goodsNums i').text(goodsNum)
        $('.selectedPVAndNum .goodsPVs i').text(pv)
        $('.selectedPriceAll em i').text(price)

    }
    //渲染数据到侧边购物车
    function renderAsideShoppingCar(buyGoods) {
        var allPv = 0
        var allPrice = 0
        var str = ''
        buyGoods.forEach((item) => {
                str += `
            <div class="goodsPur">
                <div class="img">
                    <img src="${item.imgUrl}?x-oss-process=image/resize,w_220" alt="">
                </div>
                <div class="goodsIntro">
                    <div><p>${item.displayName}</p><span id="delGoods" data-id='${item.id}'>删除</span></div>
                    <span class="goodsCode">${item.code}</span>
                    <div class="priceNum">
                        <i class="price">￥${item.price}</i><em class="num">${item.num}</em>
                    </div>
                </div>
            </div>
            `
                allPv += item.pv
                allPrice += item.num * item.price
            })
            // console.log(allPv, allPrice);
        $('.asideCar .goods').html(str)
        $('.shoppingCarBottom .priceAndPV .priceAll').text('￥' + allPrice)
        $('.shoppingCarBottom .priceAndPV .PV').text(allPv)


    }
    //获取购买总数
    function getNum(buyGoods) {
        var goodsNum = 0
        for (var i = 0; i < buyGoods.length; i++) {
            goodsNum += buyGoods[i]['num']
        }
        console.log(goodsNum);
        $('.shoppingCarBottom .numAll').text(goodsNum)
        $('#elevator #goodsAll').text(goodsNum)
    }


})